<?php
/**
 * Created by PhpStorm.
 * User: august
 * Date: 2021/4/2
 * Time: 10:38
 */

namespace Aug\Tools\Exporter;


use Aug\Tools\Exporter\ExporterInterface;

class Csv implements ExporterInterface
{
    protected $fp;
    protected $file;
    protected $params;

    public function __construct($params = [])
    {
        // 也可以使用SplFileObject
        $this->params = $params;
        $this->setFile($params);
        $this->fp = @fopen($this->getFile(), 'w');
        if (!$this->fp) {
            throw new \Exception("无法创建文件，请检查目录权限");
        }
        $this->addBom();
    }

    public function setFile($params)
    {
        if (!empty($params['file'])) {
            $this->file = $params['file'];
        } else {
            $this->file = tempnam(sys_get_temp_dir() . DIRECTORY_SEPARATOR, 'tmp_') . '.csv';
        }
    }

    public function getFile()
    {
        return $this->file;
    }

    public function addBom()
    {
        fputs($this->fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
    }

    public function addRow($data)
    {
        foreach ($data as &$val) {
            if (is_numeric($val) && abs($val) > 1e11) {
                $val = "'" . $val;
            }
        }
        unset($val);

        fputcsv($this->fp, $data);
    }

    public function __destruct()
    {
        fclose($this->fp);
    }
}